import React, { Component, PropTypes } from 'react';
import { Affix, Button, Form, Icon, message, Radio, Select, Spin } from 'antd';
import { messages } from "share/common";
import CompactInput from "components/compact-input";
import Chooser from "components/chooser";
import menuRoute from "routes/menuRoute";
import formService from 'containers/setting/form/form.service'

const { Item } = Form;
const { Group } = Radio;
const { Option } = Select;

class ContractProperty extends Component {

  state = {
    loading: false,
    formRadioConfig: {
      applicationEnabled: false, //关联申请单
      relatedApplicationRequired: false, //关联申请单是否必填
      createSupplier: 'false',
    },
    applicationFormType: {
      range: 'ALL',
      value: []
    }
  };

  componentDidMount () {
    this.init()
  }

  init = () => {
    const { form } = this.context;
    let relatedApplicationProperty = JSON.parse(form.customFormPropertyMap['related.application.property'] || '{}');
    let formRadioConfig = {};
    let { formDataList } = relatedApplicationProperty;
    formRadioConfig.applicationEnabled = relatedApplicationProperty.enable || false;
    formRadioConfig.relatedApplicationRequired = relatedApplicationProperty.required || false;
    formRadioConfig.createSupplier = form.customFormPropertyMap['create.supplier'] || 'false'
    this.setState({
      formRadioConfig,
      applicationFormType: {
        range: formDataList.length === 0 ? 'ALL' : 'PART',
        value: formDataList
      }
    })
  }

  handleRadioStatusChange = (value, key) => {
    let { formRadioConfig } = this.state;
    formRadioConfig[key] = value;
    this.setState({ formRadioConfig });
    if (key === 'applicationEnabled' && value === false) {
      this.setState({
        applicationFormType: {
          range: 'ALL',
          value: []
        }
      });
    }
  };

  handleApplicationChange = values => {
    let applicationFormType = Object.assign({}, this.state.applicationFormType, { value: values });
    this.setState({ applicationFormType });
  }

  validateData = () => {
    const { applicationFormType } = this.state;
    if (applicationFormType.value.length === 0 && applicationFormType.range === 'PART') {
      message.error(messages('request-2.key449')/*请选择关联申请单列表*/);
      return false;
    }
    return true;
  }

  handleSave = () => {
    const { formOID } = this.context;
    this.props.form.validateFieldsAndScroll(err => {
      if (!err && this.validateData()) {
        let params = this.processValue();
        this.setState({ loading: true })
        formService.saveNewForm(params).then(res => {
          this.setState({ loading: false });
          message.success(messages('common.save.success', { arg1: res.data.formName })/*{arg1} 保存成功*/);
          this.props.refreshBase(formOID, 'property');
        }).catch(() => {
          this.setState({ loading: false })
          message.error(messages('common.save.filed')/*保存失败*/);
        })
      }
    })
  };

  processValue = () => {
    const { form } = this.context;
    let params = {
      ...form,
      customFormFields: form.customFormFields
    };
    params.customFormPropertyMap = this.processPropertyMap();
    return params;
  }

  processPropertyMap = () => {
    const { formRadioConfig, applicationFormType } = this.state;
    let propertyMap = {};
    if (!formRadioConfig.applicationEnabled) formRadioConfig.relatedApplicationRequired = false;
    propertyMap['related.application.property'] = JSON.stringify({
      enable: formRadioConfig.applicationEnabled,
      formDataList: applicationFormType.value,
      required: formRadioConfig.relatedApplicationRequired
    });
    propertyMap['create.supplier'] = formRadioConfig.createSupplier;
    return propertyMap;
  }

  goBack = value => {
    const { close } = this.context;
    if (close) {
      close(value);
    } else {
      this.context.router.push(menuRoute.getRouteItem('form-list', 'key').url);
    }
  };

  render () {
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 8, offset: 1 },
    };
    const { loading, applicationFormType, formRadioConfig } = this.state;
    const { form } = this.context;
    let priorityValue = {
      levelCode: form.fromType === 2 ? "SET_OF_BOOK" : "COMPANY",
      levelOrgId: form.fromType === 2 ? form.setOfBooksId : form.companyOID,
    };
    return (
      <div className='form-new-edit new-form form-detail-base'>
        <Spin spinning={loading}>
          <Form>
            <Item
              required
              {...formItemLayout}
              label={messages('request-2.key44')/*关联申请单*/}>
              <Group
                value={formRadioConfig.applicationEnabled}
                onChange={e => this.handleRadioStatusChange(e.target.value,'applicationEnabled')}>
                <Radio value={true}>{messages('request-2.key32')/*关联*/}</Radio>
                <Radio style={{ marginLeft: 50 }} value={false}>{messages('request-2.key46')/*不关联*/}</Radio>
              </Group>
            </Item>
            {formRadioConfig.applicationEnabled &&
              <div>
                <Item
                  {...formItemLayout}
                  label={<span><Icon type="enter" className="rotate-icon"/>{messages('request-2.key412')/*可关联表单列表*/}</span>}>
                  <CompactInput>
                    <Select
                      style={{width: '100%'}}
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                      onChange={value => this.setState({ applicationFormType: { range: value, value: [] } })}
                      value={applicationFormType.range}
                    >
                      <Option key={'ALL'}>{messages('common.all')/*全部*/}</Option>
                      <Option key={'PART'}>{messages('request-2.key10')/*部分*/}</Option>
                    </Select>
                    <Chooser
                      placeholder={applicationFormType.range === 'ALL' ? messages('common-1.key421')/*通用*/ : messages('common.select')/*请选择*/}
                      type='available_request_list'
                      labelKey='formName'
                      valueKey='formOID'
                      listExtraParams={{
                        setOfBooksId: priorityValue.levelCode === 'SET_OF_BOOK' ? priorityValue.levelOrgId : undefined,
                        companyOID: priorityValue.levelCode === 'COMPANY' ? priorityValue.levelOrgId : undefined,
                      }}
                      disabled={applicationFormType.range === 'ALL'}
                      onChange={values => this.handleApplicationChange(values)}
                      value={applicationFormType.value}
                    />
                  </CompactInput>
                </Item>
                <Item
                  required
                  {...formItemLayout}
                  label={<span><Icon type="enter" className="rotate-icon"/>{messages('request-2.key417')/*关联申请单必填*/}</span>}>
                  <Group
                    value={formRadioConfig.relatedApplicationRequired}
                    onChange={e => this.handleRadioStatusChange(e.target.value,'relatedApplicationRequired')}>
                    <Radio value={true}>{messages('request-2.key326')/*必填*/}</Radio>
                    <Radio style={{ marginLeft: 50 }} value={false}>{messages('request-2.key327')/*不必填*/}</Radio>
                  </Group>
                </Item>
              </div>
            }
            <Item label={messages('request-2.key450')/*新建供应商*/}  {...formItemLayout} required>
              <Group
                style={{width: '100%'}}
                value={formRadioConfig.createSupplier}
                onChange={e => this.handleRadioStatusChange(e.target.value,'createSupplier')}
              >
                <Radio style={{marginRight: 50}} value="false">{messages('request-2.key56')/*不可创建*/}</Radio>
                <Radio style={{marginRight: 50}} value="true">{messages('request-2.key351')/*可创建：供应商+银行账号*/}</Radio>
                <Radio value="bankOnly">{messages('request-2.key352')/*可创建：银行账号*/}</Radio>
              </Group>
              <div style={{color: '#989898'}}>
                {messages('request-2.key451')/*控制是否允许新建合同时，直接创建供应商或供应商的银行账号*/}
              </div>
            </Item>
          </Form>
        </Spin>
        <Affix offsetBottom={0} className="bottom-bar">
          <Button type="primary" loading={loading} onClick={this.handleSave}>{messages('common.ok')/*确定*/}</Button>
          <Button style={{marginLeft: 15}} onClick={() => this.goBack(true)}>{messages('common.back')/*返回*/}</Button>
        </Affix>
      </div>
    )
  }
}

ContractProperty.contextTypes = {
  router: PropTypes.object,
  close: PropTypes.any,
  formOID: PropTypes.string,
  form: PropTypes.object
}

ContractProperty.propTypes = {
  refreshBase: PropTypes.func
};

export default Form.create()(ContractProperty);
